package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.query.ObjectQuery;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PermissionName;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;

    @RequiresPermissions("permission:index")
    @PermissionName("权限主页")
    @RequestMapping("index")
    public String index(Model model, @ModelAttribute("qo") ObjectQuery qo) {
        return "permission/list";
    }

    @RequiresPermissions("permission:list")
    @PermissionName("权限查询")
    @RequestMapping("list")
    @ResponseBody
    public PageResult<Permission> list(Model model, @ModelAttribute("qo") ObjectQuery qo) {
        PageResult<Permission> list = permissionService.query(qo);
        return list;
    }

    @RequestMapping("selectAll")
    @ResponseBody
    public PageResult<Permission> selectAll(Model model, @ModelAttribute("qo") ObjectQuery qo) {
        List<Permission> list = permissionService.getAll();
        return new PageResult<>(list.size(),list);
    }

    @RequestMapping("queryPermissionByRoleId")
    @ResponseBody
    public PageResult<Permission> queryPermissionByRoleId(Long roleId) {
        PageResult<Permission> list = permissionService.queryPermissionByRoleId(roleId);
        return list;
    }


    @RequiresPermissions("permission:delete")
    @PermissionName("权限删除")
    @ResponseBody
    @RequestMapping("delete")
    public JsonResult delete(Long id) {
        JsonResult jsonResult = new JsonResult();
        try {
            if (id != null) {
                permissionService.delete(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.markErrorMsg("删除权限失败");
        }
        return jsonResult;
    }

    @RequiresPermissions("permission:reload")
    @PermissionName("权限加载")
    @RequestMapping("reload")
    @ResponseBody
    public void reload() {
        permissionService.reload();


    }
}
